package com.myproject.zhujiemian;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itheima.tencentqq52.R;
import com.myproject.database.MYdatabase;
import com.myproject.database.Time;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class TaskJishi extends Activity implements Runnable {

	private Time taskDB;
	private SQLiteDatabase timeWriter;
	private MYdatabase deletetask;
	private SQLiteDatabase dbWriter;
	
	private static final String TAG = "TaskJishi";

	/**
	 * 当前所经过的时间
	 */
	private long time = 0;

	/**
	 * 开始时间
	 */
	private long startTime;

	private Handler handler;

	/**
	 * 用于显示时间
	 */
	private TextView tv_letusrun;

	/**
	 * 用于列表显示分记时间
	 */
	private ListView listView;

	/**
	 * 开始按钮
	 */
	private Button startButton;
	/**
	 * 撤销按钮
	 */
	private Button deleteButton;

	/**
	 * 暂停按钮
	 */
	private Button pauseButton;

	/**
	 * 重置按钮
	 */
	private Button resetButton;

	/**
	 * 分记时间数据
	 */

	/**
	 * 秒表的当前状态 分为正在运行、暂停、停止三种状态
	 */
	private int state = 0;

	private static int STATE_RUNNING = 1;
	private static int STATE_STOP = 0;
	private static int STATE_PAUSE = 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.jishiqimain);
		taskDB = new Time(this);
		timeWriter = taskDB.getWritableDatabase();
		deletetask = new MYdatabase(this);
		dbWriter = deletetask.getWritableDatabase();
		// 读取环境信息（偏好 ）
		readEnvironment();
		// Toast.makeText(this, "环境已读取", Toast.LENGTH_LONG).show();

		// 开始按钮
		startButton = (Button) findViewById(R.id.bt_start);
		startButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				onStartClick(view);
			}
		});

		// 暂停按钮
		pauseButton = (Button) findViewById(R.id.bt_pause);
		pauseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				onPauseClick(view);
			}
		});

		// 重置按钮
		resetButton = (Button) findViewById(R.id.reset);
		// resetButton.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View view) {
		// onResetClick(view);
		// }
		// });

		tv_letusrun = (TextView) findViewById(R.id.tv_letusrun);
		// listView = (ListView) findViewById(R.id.ListView01);
		
		deleteButton = (Button) findViewById(R.id.bt_deletetask2);

		// 创建 handler
		handler = new Handler();

		// 设置各按钮
		setButtons();

		// 设置时间显示
		if (state == STATE_STOP) {
			tv_letusrun.setText("Let's Study!");
		} else if (state == STATE_PAUSE) {
			tv_letusrun.setText(getFormatTime(time));
		}

	}

	/**
	 * 根据状态设置按钮显示于不显示
	 */
	private void setButtons() {
		switch (state) {
		case 1:// 如果正在运行
			startButton.setVisibility(View.GONE);
			pauseButton.setVisibility(View.VISIBLE);
			deleteButton.setVisibility(View.GONE);
			resetButton.setVisibility(View.GONE);
			resetButton.setEnabled(false);
			break;
		case 2:// 如果暂停中
			startButton.setVisibility(View.VISIBLE);
			pauseButton.setVisibility(View.GONE);
			deleteButton.setVisibility(View.VISIBLE);
			resetButton.setVisibility(View.VISIBLE);
			resetButton.setEnabled(true);
			break;
		case 0:// 如果停止中
			startButton.setVisibility(View.VISIBLE);
			pauseButton.setVisibility(View.GONE);
			deleteButton.setVisibility(View.GONE);
			resetButton.setVisibility(View.VISIBLE);
			resetButton.setEnabled(false);
			break;
		default:
			break;
		}
	}

	/**
	 * 读取环境
	 */
	@SuppressWarnings("unchecked")
	private void readEnvironment() {
		SharedPreferences sharedPreferences = getSharedPreferences(
				"environment", MODE_PRIVATE);
		state = sharedPreferences.getInt("state", STATE_STOP);
		startTime = sharedPreferences.getLong("startTime", 0);
		time = sharedPreferences.getLong("time", 0);

	}

	/**
	 * 保存环境
	 */
	private void saveEnvironment() {
		SharedPreferences sharedPreferences = getSharedPreferences(
				"environment", MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putInt("state", state);
		editor.putLong("time", time);
		editor.putLong("startTime", startTime);
		editor.commit();

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (state == STATE_RUNNING) {// 如果正在运行
			handler.removeCallbacks(this);
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 保存环境
		saveEnvironment();
		// Toast.makeText(this, "当前环境已保存", Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (state == STATE_RUNNING) {// 如果正在运行
			handler.post(this);
		}
	}

	/**
	 * 点击重置
	 * 
	 * @param view
	 */
	// protected void onResetClick(View view) {
	// //设置状态为停止
	// state = STATE_STOP;
	//
	// //不再刷新
	// if (state == STATE_RUNNING){//如果正在运行
	// handler.removeCallbacks(this);
	// }
	//
	//
	// //设置时间显示
	// time = 0;
	// tv_letusrun.setText(getFormatTime(time));
	//
	// // 设置各按钮
	// setButtons();
	// }

	/**
	 * 点击暂停
	 * 
	 * @param view
	 */
	protected void onPauseClick(View view) {
		// 不再刷新
		if (state == STATE_RUNNING) {// 如果正在运行
			handler.removeCallbacks(this);
		}

		// 设置状态为暂停
		state = STATE_PAUSE;

		// 设置各按钮
		setButtons();
	}

	/**
	 * 点击开始
	 * 
	 * @param view
	 */
	protected void onStartClick(View view) {
		startTime = new Date().getTime() - time;

		handler.post(this);

		// 设置状态为正在运行
		state = STATE_RUNNING;

		// 设置各按钮
		setButtons();
	}

	@Override
	public void run() {
		handler.postDelayed(this, 50);
		time = new Date().getTime() - startTime;
		tv_letusrun.setText(getFormatTime(time));
	}

	/**
	 * 得到一个格式化的时间
	 * 
	 * @param time
	 *            时间 毫秒
	 * @return 分：秒：毫秒
	 */
	private String getFormatTime(long time) {
		long millisecond = time % 1000;
		long second = (time / 1000) % 60;
		long minute = time / 1000 / 60;
		long hour = minute/60;

		// 秒以下的只显示一位
		String strMillisecond = "" + (millisecond / 100);
		// 秒显示两位
		String strSecond = ("00" + second)
				.substring(("00" + second).length() - 2);
		// 分显示两位
		String strMinute = ("00" + minute)
				.substring(("00" + minute).length() - 2);
		// 小时显示两位
		String strHour = ("0" + hour)
				.substring(("0" + hour).length() - 2);
		
		return strHour + ":" + strMinute + ":" + strSecond;
	}

	// 跳转到任务页面
	public void ToRenwuPage(View view) {
		addtime();
		state = STATE_STOP;

		// 不再刷新
		if (state == STATE_RUNNING) {// 如果正在运行
			handler.removeCallbacks(this);
		}

		// 设置时间显示
		time = 0;
		tv_letusrun.setText(getFormatTime(time));

		// 设置各按钮
		setButtons();
		
		Log.e(TAG, "任务的ID是：" + String.valueOf(getIntent().getIntExtra(MYdatabase.ID, 0)));
		dbWriter.delete(MYdatabase.TABLE_NAME, "_id="
			+ getIntent().getIntExtra(MYdatabase.ID, 0), null);

		Intent intent = new Intent(this, MainActivity.class);
		intent.setAction("android.intent.action.MAIN");
		startActivity(intent);
	}

	public void addtime() {
		ContentValues t = new ContentValues();
		t.put(Time.TASKTIME, getFormatTime(time));
		timeWriter.insert(Time.TABLE_NAME, null, t);
	}

	public void DeleteTask2(View view) {

		Intent intent = new Intent(this, MainActivity.class);
		intent.setAction("android.intent.action.MAIN");
		startActivity(intent);
	}

}
